package openvpn

import (
	"bufio"
	"fmt"
	"os"
	"strings"
	"vpn/app/utils/file_handle"
)

type OpenvpnConfig struct {
	Subnet           string
	Mask             string
	ClientConnEnable bool
}

// 读取配置文件并返回 server.conf 配置的 IP 和子网掩码
func ReadConfig(filePath string) (vpnConf OpenvpnConfig, err error) {
	conf := OpenvpnConfig{Subnet: "", Mask: ""}
	if exist, _ := file_handle.Exists(filePath); !exist {
		return conf, err
	}
	file, err := os.Open(filePath)
	if err != nil {
		return conf, err
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		line = strings.TrimSpace(line)
		if strings.HasPrefix(line, "server.conf") {
			parts := strings.Fields(line)
			if len(parts) >= 3 {
				ip := parts[1]
				mask := parts[2]
				conf.Subnet, conf.Mask = ip, mask
				break
			}
		}
		if strings.HasPrefix(line, "client-to-client") {
			conf.ClientConnEnable = true
		} else {
			conf.ClientConnEnable = false
		}
	}
	if err := scanner.Err(); err != nil {
		return conf, err
	}
	return conf, nil
}

func main() {
	configPath := "/etc/openvpn/service.conf"
	conf, err := ReadConfig(configPath)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Printf("Server IP: %s\n", conf.Subnet)
	fmt.Printf("Subnet Mask: %s\n", conf.Mask)
}
